<template>
  <div class="travel-check-container">
    <!-- 背景图 -->
    <div class="background"></div>

    <!-- 主体内容 -->
    <div class="content">
      <!-- 标题 -->
      <h1 class="title">合规导游、旅行社信息验证</h1>
      <p class="desc">
        为确保您的旅程得到更好保障，你可以提前验证<br />
        导游、旅行社及电子合同的官方备案信息
      </p>

      <!-- 功能说明 -->
      <ul class="features">
        <li>· 导游手机号或导游证号可验证导游资格备案</li>
        <li>· 旅行社名称可验证旅行社的相关工商注册信息</li>
        <li>· 电子合同统一编号可验证合同是否真实有效</li>
      </ul>

      <!-- 查询卡片 -->
      <div class="form-card">
        <van-tabs v-model:active="activeTab" background="transparent" color="#FFA500" title-active-color="#FFA500"
          title-inactive-color="#666" line-width="auto">
          <!-- 查询导游 -->
          <van-tab title="查询导游">
            <!-- 下拉选择框 -->
            <div class="dropdown-select">
              <div class="select-header" @click="showGuideOptions = !showGuideOptions">
                <span class="selected-text">{{ selectedGuideType }}</span>
                <van-icon name="arrow-down" size="14" color="#FFA500" />
              </div>
              <div v-show="showGuideOptions" class="options-list">
                <div v-for="item in guideOptions" :key="item.value" class="option-item"
                  :class="{ active: item.value === selectedGuideType }" @click="selectGuideOption(item)">
                  <van-icon v-if="item.value === selectedGuideType" name="check" size="12" color="#FFA500" />
                  <span class="option-label">{{ item.label }}</span>
                </div>
              </div>
            </div>

            <!-- 输入框 -->
            <van-field v-model="guideValue" placeholder="请输入手机号或导游证号查询" clearable input-align="left"
              style="margin-top: 10px;" />

            <!-- 按钮 -->
            <van-button color="#FFA500" 
            type="primary" 
            block size="large" 
            style="margin-top: 16px" @click="queryGuideHandler">
              查询导游
            </van-button>
          </van-tab>

          <!-- 查询旅行社 -->
          <van-tab title="查询旅行社">
            <van-field v-model="agencyName" placeholder="请输入旅行社名" clearable input-align="left" />
            <!-- 验证码行 -->
            <div class="captcha-row" style="display: flex; align-items: center; gap: 10px; margin-top: 10px;">
              <van-field v-model="captcha" placeholder="验证码" clearable style="flex: 1; max-width: 200px;" />
              <img :src="captchaImg" alt="验证码" class="captcha-img" @click="refreshCaptcha"
                style="width: 90px; height: 40px; cursor: pointer;" />
            </div>
            <van-button color="#FFA500" 
            type="primary" 
            block size="large" 
            style="margin-top: 16px" @click="queryAgencyHandler">
              查询旅行社
            </van-button>
          </van-tab>

          <!-- 查询电子合同 -->
          <van-tab title="查询电子合同">
            <van-field v-model="contractNumber" placeholder="请输入电子合同统一编号查询" clearable input-align="left" />
            <van-button color="#FFA500" type="primary" block size="large" style="margin-top: 16px"
              @click="queryContractHandler">
              查询电子合同
            </van-button>
          </van-tab>
        </van-tabs>

        <div class="wish">祝您旅途愉快 ~</div>
      </div>
    </div>

    <!-- 数据来源提示 -->
    <div class="source-note">
      *数据查询结果来源于全国旅游监管服务平台
    </div>

    <!-- 导游结果弹窗 -->
    <van-popup v-model:show="showGuidePopup" round closeable close-icon-position="bottom-right"
      :style="{ width: '90%', height: 'auto', backgroundColor: '#FFA500', padding: '16px' }" @close="onCloseGuidePopup">
      <div class="popup-title">导游查询结果</div>
      <div class="result-item">
        <p><strong>姓名：</strong>{{ guideResult.guide_name }}</p>
        <p><strong>手机号：</strong>{{ guideResult.guide_phone_number }}</p>
        <p><strong>导游证号：</strong>{{ guideResult.license_number }}</p>
        <p><strong>资格状态：</strong>{{ formatStatus(guideResult.qualification_status) }}</p>
      </div>
      <div class="footer-note">*数据来源于全国旅游监管服务平台</div>
    </van-popup>

    <!-- 旅行社结果弹窗 -->
    <van-popup v-model:show="showAgencyPopup" round closeable close-icon-position="bottom-right"
      :style="{ width: '90%', height: '80%', backgroundColor: '#FFA500', padding: '16px' }" @close="onCloseAgencyPopup">
      <div class="popup-title">旅行社查询结果</div>
      <div class="results-list">
        <div v-for="(item, index) in agencyResults" :key="index" class="result-item">
          <div class="result-content">
            <p><strong>旅行社名称：</strong>{{ item.name }}</p>
            <p><strong>经营许可证号：</strong>{{ item.licenseNo }}</p>
            <p><strong>统一社会信用代码：</strong>{{ item.creditCode }}</p>
          </div>
        </div>
      </div>
      <div class="footer-note">*数据来源于全国旅游监管服务平台</div>
    </van-popup>

    <!-- 合同结果弹窗 -->
    <van-popup v-model:show="showContractPopup" round closeable close-icon-position="bottom-right"
      :style="{ width: '90%', height: 'auto', backgroundColor: '#FFA500', padding: '16px' }"
      @close="onCloseContractPopup">
      <div class="popup-title">电子合同查询结果</div>
      <div class="result-item">
        <p><strong>合同编号：</strong>{{ contractResult.number }}</p>
        <p><strong>状态：</strong>{{ formatContractStatus(contractResult.status) }}</p>
        <p><strong>签署时间：</strong>{{ contractResult.signTime }}</p>
        <p><strong>甲方：</strong>{{ contractResult.partyA }}</p>
        <p><strong>乙方：</strong>{{ contractResult.partyB }}</p>
      </div>
      <div class="footer-note">*数据来源于全国旅游监管服务平台</div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { queryGuide, queryAgency, queryContract } from '@/api/index';

// 当前激活的 tab
const activeTab = ref(0);

const loading = ref(false);

// 查询导游
const showGuideOptions = ref(false);
const selectedGuideType = ref('手机号');
const guideOptions = [
  { label: '手机号', value: '手机号' },
  { label: '导游证号', value: '导游证号' }
];
const guideValue = ref('');

const selectGuideOption = (item) => {
  selectedGuideType.value = item.value;
  showGuideOptions.value = false;
};

// 查询旅行社
const agencyName = ref('');
const captcha = ref('');
const captchaImg = ref('');

// 刷新验证码
const refreshCaptcha = () => {
  // 直接更新验证码图片URL
  captchaImg.value = `/api/captcha?t=${Date.now()}`;
};

// 初始化时获取验证码
refreshCaptcha();

// 查询电子合同
const contractNumber = ref('');

// 弹窗控制
const showGuidePopup = ref(false);
const guideResult = ref(null);

const showAgencyPopup = ref(false);
const agencyResults = ref([]);

const showContractPopup = ref(false);
const contractResult = ref(null);

// 状态映射
const formatStatus = (status) => {
  const map = {
    qualified: '合格',
    unqualified: '不合格',
    pending: '待审核',
    suspended: '已暂停'
  };
  return map[status] || status;
};

// 状态映射函数
const formatContractStatus = (status) => {
  const map = {
    valid: '有效',
    invalid: '无效'
  };
  return map[status] || status;
};

// 查询方法

// 修改导游查询结果处理
const queryGuideHandler = async () => {
  if (!guideValue.value) {
    alert('请输入查询内容');
    return;
  }

  loading.value = true;
  try {
    const response = await queryGuide({
      searchType: selectedGuideType.value === '手机号' ? 'phone' : 'license',
      searchValue: guideValue.value
    });

    if (response.guideId && response) {
      guideResult.value = {
        guide_id: response.guideId,
        guide_name: response.guideName,
        guide_phone_number: response.guidePhoneNumber,
        license_number: response.licenseNumber,
        qualification_status: response.qualificationStatus
      };
      showGuidePopup.value = true;
    } else {
      alert(response.message || '未查询到数据');
    }
  } catch (error) {
    console.error('查询导游信息失败:', error);
    alert('查询失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 查询旅行社方法
const queryAgencyHandler = async () => {
  if (!agencyName.value || !captcha.value) {
    alert('请填写旅行社名称和验证码');
    return;
  }

  loading.value = true;
  try {
    const response = await queryAgency({
      agencyName: agencyName.value,
      captcha: captcha.value
    });

    if (Array.isArray(response) && response) {
      agencyResults.value = response.map(item => ({
        id: item.id,
        name: item.agencyName,
        licenseNo: item.licenseNumber,
        creditCode: item.creditCode
      }));
      showAgencyPopup.value = true;
      // 查询成功后清空验证码输入框并刷新验证码
      captcha.value = '';
      refreshCaptcha();
    } else {
      // 查询失败时刷新验证码
      refreshCaptcha();
      alert(response.message || '未查询到数据');
    }
  } catch (error) {
    // 出现异常时刷新验证码
    refreshCaptcha();
    console.error('查询旅行社信息失败:', error);
    alert('查询失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

//查询电子合同方法 
const queryContractHandler = async () => {
  if (!contractNumber.value) {
    alert('请输入电子合同统一编号');
    return;
  }

  loading.value = true;
  try {
    const response = await queryContract({
      contractNo: contractNumber.value
    });

    if (response.contractNo && response) {
      contractResult.value = {
        id: response.id,
        number: response.contractNo,
        status: response.status,
        signTime: response.signDate,
        partyA: response.partyA,
        partyB: response.partyB
      };
      showContractPopup.value = true;
    } else {
      alert(response.message || '未查询到数据');
    }
  } catch (error) {
    console.error('查询电子合同失败:', error);
    alert('查询失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 关闭弹窗
const onCloseGuidePopup = () => { showGuidePopup.value = false; };
const onCloseAgencyPopup = () => { showAgencyPopup.value = false; };
const onCloseContractPopup = () => { showContractPopup.value = false; };
</script>

<style scoped>
.travel-check-container {
  width: 100%;
  height: 100vh;
  position: relative;
  background-image: url('/query-bgr.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  color: white;
  padding-top: 20px;
  box-sizing: border-box;
  overflow: hidden;
}

.background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  z-index: -1;
}

.content {
  text-align: center;
  width: auto;
  max-width: 500px;
  padding: 16px;
  border-radius: 16px;
  flex-grow: 1;
}

.title {
  font-size: 1.7rem;
  font-weight: bold;
  margin: 10px 0;
  line-height: 1.4;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 1);
}

.desc {
  font-size: 0.95rem;
  line-height: 1.6;
  margin-top: 20px;
  margin-bottom: 16px;
  opacity: 0.95;
  text-align: left;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.8);
}

.features {
  list-style: none;
  padding: 0;
  text-align: left;
  font-size: 0.5rem;
  color: #fff;
  opacity: 0.9;
  margin-bottom: 25px;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.features li {
  margin-bottom: 6px;
  line-height: 1.4;
}

.form-card {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 6px;
  padding: 20px 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

/* 下拉选择框样式 */
.dropdown-select {
  width: 100%;
  position: relative;
  margin-bottom: 10px;
  box-sizing: border-box;
}

.select-header {
  width: 100%;
  padding: 10px 12px;
  background: #fff;
  border: 1px solid #FFA500;
  border-radius: 4px;
  font-size: 0.95rem;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  user-select: none;
  box-sizing: border-box;
}

.selected-text {
  color: #FFA500;
  font-weight: 500;
}

.options-list {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  background: #fff;
  border: 1px solid #FFA500;
  border-top: none;
  border-radius: 0 0 6px 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 10;
  overflow: hidden;
  box-sizing: border-box;
}

.option-item {
  padding: 10px;
  font-size: 0.9rem;
  color: #333;
  cursor: pointer;
  border-bottom: 1px solid #eee;
  transition: background 0.2s ease;
  display: flex;
  align-items: center;
  box-sizing: border-box;
}

.option-item:last-child {
  border-bottom: none;
}

.option-item:hover {
  background: #f7f7f7;
}

.option-item.active {
  background: #fff8e1;
  color: #FFA500;
}

.option-item.active .van-icon {
  color: #FFA500;
}

.option-item .van-icon {
  opacity: 0;
  transition: opacity 0.2s ease;
}

.option-item.active .van-icon {
  opacity: 1;
}

.captcha-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 10px;
  max-width: 250px;
}

.captcha-img {
  width: 90px;
  height: 40px;
  border: 1px solid #ddd;
  cursor: pointer;
}

.wish {
  font-size: 0.95rem;
  color: #FFA500;
  margin-top: 16px;
  font-weight: 500;
}


.source-note {
  font-size: 0.8rem;
  color: white;
  opacity: 0.7;
  text-align: center;
  margin-top: auto;
  padding-bottom: 60px;
}

/* 弹窗样式 */
.popup-title {
  font-size: 1.2rem;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-bottom: 16px;
}

.result-item {
  background: white;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.result-item p {
  margin: 4px 0;
  font-size: 0.9rem;
  color: #333;
}

.results-list {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 8px;
}

.footer-note {
  font-size: 0.8rem;
  color: #666;
  margin-top: 12px;
  text-align: center;
}
</style>